﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.handler;
using InfonavaEye.Handler;
using InfonavaEye.util;
using JumpKick.HttpLib.Streams;
using Sylan.Common.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace InfonavaEye
{
    public partial class LoadingForm : Form
    {
        private CameraHandler cameraHandler = CameraHandler.Instance;
        private PLCHandler plcHandler = PLCHandler.Instance;
        private LightHandler lightHandler = LightHandler.Instance;

        private int cameraStatus = 0;
        private int plcStatus = 0;
        private int lightStatus = 0;
        private int networkStatus = 0;

        public LoadingForm()
        {
            InitializeComponent();
            progressBar1.ProcessChanged += ProgressBar1_ProcessChanged;
        }

        private void LoadingForm_Load(object sender, EventArgs e)
        {
            SoundHelper.PlayAudio("welcome.wav");
            initConfig();
            startDevice();

            //延迟14秒检查是否还没启动成功：就打开刷新按钮。
            Task.Run(async () =>
            {
                await Task.Delay(14 * 1000);
                if (progressBar1.Value < 100)
                {
                    this.btnRefresh.Visible = true;
                }
            });
        }

        private void initConfig() {
            //软件首次使用日期
            if (String.IsNullOrEmpty(Config.APP_FIRST_USE_DATE)) {
                string firstUseDate = DateTime.Now.ToString("yyyy-MM-dd");
                Config.APP_FIRST_USE_DATE = firstUseDate;
                Config.INI.WriteValue("device", "APP_FIRST_USE_DATE", firstUseDate);
            }
        }

        /// <summary>
        /// 启动硬件设备
        /// </summary>
        private void startDevice()
        {
            cameraStatus = 0;
            plcStatus = 0;
            lightStatus = 0;
            networkStatus = 0;
            progressBar1.Value = 25;
            this.pictureBox1.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;
            this.pictureBox2.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;
            this.pictureBox3.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;
            this.pictureBox4.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;
            this.pictureBox5.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;
            this.pictureBox6.BackgroundImage = global::InfonavaEye.Properties.Resources.round_uncheck;

            cameraHandler.openCompleteDelegate += CameraHandler_openCompleteDelegate;
            plcHandler.PLCInitCompleteDelegate += PlcHandler_PLCInitCompleteDelegate;
            lightHandler.LightConnectedDelegate += LightHandler_LightConnectedDelegate;
            ThreadHelper.ExcuteThreadTask(() =>
            {
                try
                {
                    cameraHandler.open(true);
                    plcHandler.StartPLC();
                    lightHandler.Start();
                    this.CheckNetwork();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("打开设备发生异常，{0},{1}", ex.Message, ex.StackTrace);
                }
            }, 50);
        }

        private void ProgressBar1_ProcessChanged(float processValue)
        {
            this.Invoke(new Action(() =>
            {
                //预计剩余时间（s）
                int leftTime = processValue < 10 ? 12 : processValue < 25 ? 10 : processValue < 50 ? 6 : processValue < 75 ? 4 : 2;
                this.lblLeftTime.Text = String.Format("预计剩余时间{0}S", leftTime.ToString().PadLeft(2));
                this.lblProcessText.Text = String.Format("{0}%", processValue);
            }));
        }

        /// <summary>
        /// 检查网络
        /// </summary>
        /// <returns></returns>
        private void CheckNetwork()
        {
            string host = "www.baidu.com";
            Ping p = new Ping();
            try
            {
                PingReply reply = p.Send(host, 3000);
                if (reply.Status == IPStatus.Success)
                {
                    this.networkStatus = 1;
                    this.calcProcess();
                    this.Invoke(new Action(() =>
                    {
                        this.pictureBox3.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("检查网络时发生异常，{0},{1}", ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        ///计算进度
        /// </summary>
        private void calcProcess()
        {
            var process = (cameraStatus + plcStatus + lightStatus + networkStatus) * 25;
            this.progressBar1.Value = process;
            Console.WriteLine("process:" + process);
            if (process >= 100)
            {
                Task.Run(async () =>
                {
                    await Task.Delay(800);
                    this.DialogResult = DialogResult.OK;
                    this.Close();    //关闭登录窗口
                });
            }
        }

        private void LightHandler_LightConnectedDelegate()
        {
            this.lightStatus = 1;
            this.calcProcess();
            //设置默认亮度
            this.lightHandler.ChangeLuminance(Config.LIGHT_SOURCE_LUMINOSITY_DEFAULT);

            this.Invoke(new Action(() =>
            {
                this.pictureBox2.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
            }));
        }
        private void CameraHandler_openCompleteDelegate()
        {
            this.cameraStatus = 1;
            this.calcProcess();
            this.Invoke(new Action(() =>
            {
                this.pictureBox1.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
            }));
        }

        private void PlcHandler_PLCInitCompleteDelegate()
        {
            this.plcStatus = 1;
            this.calcProcess();
            this.Invoke(new Action(() =>
            {
                this.pictureBox4.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
                this.pictureBox5.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
                this.pictureBox6.BackgroundImage = global::InfonavaEye.Properties.Resources.round_check_fill;
            }));
        }

        private void LoadingForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            cameraHandler.openCompleteDelegate -= CameraHandler_openCompleteDelegate;
            plcHandler.PLCInitCompleteDelegate -= PlcHandler_PLCInitCompleteDelegate;
            lightHandler.LightConnectedDelegate -= LightHandler_LightConnectedDelegate;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            GraphicsHelper.SetGDIHigh(g);
            Color bgColor = Color.FromArgb(255, 255, 255, 255);
            GraphicsHelper.FillRoundRectangle(e.ClipRectangle, g, 20, bgColor);
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 刷新（重启硬件设备）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                if (!cameraHandler.isCameraOpening) {
                    cameraHandler.stop();
                }
                plcHandler.ClosePLC();
                lightHandler.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("关闭设备发生异常，{0},{1}", ex.Message, ex.StackTrace);
            }
            cameraHandler.openCompleteDelegate -= CameraHandler_openCompleteDelegate;
            plcHandler.PLCInitCompleteDelegate -= PlcHandler_PLCInitCompleteDelegate;
            lightHandler.LightConnectedDelegate -= LightHandler_LightConnectedDelegate;
            this.btnRefresh.Visible = false;
            this.startDevice();
        }

        private void btnShutDown_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
